package com.yzw.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzw.common.domain.EduChapter;
import com.yzw.common.domain.EduVideo;
import com.yzw.common.mapper.EduChapterMapper;
import com.yzw.common.vo.ChapterVo;
import com.yzw.common.vo.VideoVo;
import com.yzw.course.service.EduChapterService;
import com.yzw.course.service.EduVideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
*
*/
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter>
implements EduChapterService {
    @Resource
    private EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> selChapterVideoByCourseId(String courseId) {
        // 根据课程id查询章节
        LambdaQueryWrapper<EduChapter> queryWrapperChapter = new LambdaQueryWrapper<>();
        queryWrapperChapter.eq(EduChapter::getCourseId, courseId);
        List<EduChapter> eduChapters = baseMapper.selectList(queryWrapperChapter);
        // 根据课程id查询小节
        LambdaQueryWrapper<EduVideo> queryWrapperVideo = new LambdaQueryWrapper<>();
        queryWrapperVideo.eq(EduVideo::getCourseId, courseId);
        List<EduVideo> eduVideos = eduVideoService.list(queryWrapperVideo);

        List<ChapterVo> chapterVos = new ArrayList<>();

        // 遍历章节
        for (int i = 0; i < eduChapters.size(); i++) {
            EduChapter eduChapter = eduChapters.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter, chapterVo);
            chapterVos.add(chapterVo);

            List<VideoVo> videoVoList = new ArrayList<>();
            // 遍历小节
            for (int j = 0; j < eduVideos.size(); j++) {
                EduVideo eduVideo = eduVideos.get(j);
                // 判断小节里的章节id（chapterId）是否跟章节id相等
                if (eduVideo.getChapterId().equals(eduChapter.getId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo, videoVo);
                    videoVoList.add(videoVo);
                }
            }
            // 将小节封装到章节里面
            chapterVo.setChildren(videoVoList);
        }
        return chapterVos;
    }
}
